import React, { useState } from 'react';
import { Card, Form, Input, Select, Button, Table, Space, Pagination, Row, Col, Modal, message } from 'antd';
import { useNavigate } from 'react-router-dom';

const { Option } = Select;

// mock 数据
const allData = Array.from({ length: 800 }).map((_, i) => ({
  key: i + 1,
  name: '选课1',
  year: '2021-2022学年',
  term: '2021-2022第一学期',
  target: i % 3 === 0 ? '高一年级全部班级' : '一班, 二班, 三班',
  time: '2021-09-01 8:00 — 2021-09-10 18:00',
  status: ['未发布', '未开始', '进行中', '已完成'][i % 4],
}));

export default function Xk() {
  const [form] = Form.useForm();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [data, setData] = useState(allData);
  const navigate = useNavigate();

  // 查询功能
  const onSearch = () => {
    const values = form.getFieldsValue();
    let filtered = allData;
    if (values.name) filtered = filtered.filter(item => item.name.includes(values.name));
    if (values.xd && values.xd !== '全部') filtered = filtered.filter(item => item.target.includes(values.xd));
    if (values.term && values.term !== '全部') filtered = filtered.filter(item => item.term === values.term);
    if (values.status && values.status !== '全部') filtered = filtered.filter(item => item.status === values.status);
    setData(filtered);
    setPage(1);
  };

  // 重置功能
  const onReset = () => {
    form.resetFields();
    setData(allData);
    setPage(1);
  };

  // 删除功能
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除"${record.name}"吗？`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        setData(prev => prev.filter(item => item.key !== record.key));
        message.success('删除成功');
      }
    });
  };

  // 编辑、发布、完成任务、查看数据等功能（弹窗提示）
  const handleAction = (action, record) => {
    message.info(`${action}功能开发中，可在此对接页面或接口。`);
  };

  // 顶部按钮功能
  const handleTopAction = (action) => {
    if (action === '新建任务') {
      navigate('/xk/add');
    } else {
      message.info(`${action}功能开发中，可在此对接页面或接口。`);
    }
  };

  // 分页数据
  const pagedData = data.slice((page - 1) * pageSize, page * pageSize);

  const columns = [
    { title: '序号', dataIndex: 'key', width: 60, align: 'center', render: (_, __, idx) => (page - 1) * pageSize + idx + 1 },
    { title: '选课任务名称', dataIndex: 'name', align: 'center' },
    { title: '学年', dataIndex: 'year', align: 'center' },
    { title: '学期', dataIndex: 'term', align: 'center' },
    { title: '选课对象', dataIndex: 'target', align: 'center' },
    { title: '选课时间', dataIndex: 'time', align: 'center' },
    { title: '状态', dataIndex: 'status', align: 'center' },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (_, record) => {
        if (record.status === '未发布') {
          return <Space>
            <a onClick={() => handleAction('编辑', record)}>编辑</a>
            <a style={{ color: 'red' }} onClick={() => handleDelete(record)}>删除</a>
            <a style={{ color: '#1677ff' }} onClick={() => handleAction('发布', record)}>发布</a>
          </Space>;
        } else if (record.status === '未开始') {
          return <Space>
            <a style={{ color: '#1677ff' }} onClick={() => handleAction('查看选课数据', record)}>查看选课数据</a>
            <a style={{ color: 'red' }} onClick={() => handleDelete(record)}>删除</a>
          </Space>;
        } else if (record.status === '进行中') {
          return <Space>
            <a style={{ color: '#1677ff' }} onClick={() => handleAction('查看选课数据', record)}>查看选课数据</a>
            <a style={{ color: 'red' }} onClick={() => handleDelete(record)}>删除</a>
            <a onClick={() => handleAction('完成任务', record)}>完成任务</a>
          </Space>;
        } else {
          return <Space>
            <a style={{ color: '#1677ff' }} onClick={() => handleAction('查看选课数据', record)}>查看选课数据</a>
            <a style={{ color: 'red' }} onClick={() => handleDelete(record)}>删除</a>
          </Space>;
        }
      }
    },
  ];

  return (
    <div style={{ padding: 16, background: '#f5f6fa', minHeight: '100vh' }}>
      <Card style={{ borderRadius: 12, boxShadow: '0 2px 8px #f0f1f2' }}>
        <div style={{ fontWeight: 600, fontSize: 18, marginBottom: 16 }}>选课设置</div>
        <div style={{ background: '#f7f9fa', borderRadius: 8, padding: 24, marginBottom: 16 }}>
          <Form layout="inline" form={form}>
            <Form.Item label="选课名称" name="name">
              <Input placeholder="请输入选课名称" allowClear style={{ width: 180 }} />
            </Form.Item>
            <Form.Item label="学段" name="xd">
              <Select defaultValue="小学" style={{ width: 120 }}>
                <Option value="小学">小学</Option>
                <Option value="初中">初中</Option>
                <Option value="全部">全部</Option>
              </Select>
            </Form.Item>
            <Form.Item label="学期" name="term">
              <Select defaultValue="全部" style={{ width: 120 }}>
                <Option value="全部">全部</Option>
                <Option value="2021-2022第一学期">2021-2022第一学期</Option>
              </Select>
            </Form.Item>
            <Form.Item label="状态" name="status">
              <Select defaultValue="全部" style={{ width: 120 }}>
                <Option value="全部">全部</Option>
                <Option value="未发布">未发布</Option>
                <Option value="未开始">未开始</Option>
                <Option value="进行中">进行中</Option>
                <Option value="已完成">已完成</Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={onSearch}>查询</Button>
            </Form.Item>
            <Form.Item>
              <Button onClick={onReset}>重置</Button>
            </Form.Item>
          </Form>
        </div>
        <Row justify="end" style={{ marginBottom: 12 }} gutter={8}>
          <Col><Button onClick={() => handleTopAction('下载选课模板')}>下载选课模板</Button></Col>
          <Col><Button onClick={() => handleTopAction('导入选课数据')}>导入选课数据</Button></Col>
          <Col><Button type="primary" onClick={() => handleTopAction('新建任务')}>新建任务</Button></Col>
        </Row>
        <Table
          columns={columns}
          dataSource={pagedData}
          pagination={false}
          bordered
          style={{ background: '#fff', borderRadius: 8 }}
        />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 16 }}>
          <span>共 {data.length} 条</span>
          <Pagination
            current={page}
            pageSize={pageSize}
            total={data.length}
            showSizeChanger
            pageSizeOptions={['10', '20', '50']}
            onChange={setPage}
            onShowSizeChange={(_, size) => { setPageSize(size); setPage(1); }}
            showQuickJumper
            style={{ marginRight: 8 }}
          />
          <span>每页</span>
          <Select value={pageSize} style={{ width: 80, margin: '0 8px' }} onChange={size => { setPageSize(size); setPage(1); }}>
            <Option value={10}>10 条</Option>
            <Option value={20}>20 条</Option>
            <Option value={50}>50 条</Option>
          </Select>
        </div>
      </Card>
    </div>
  );
}
